package com.leyou.item.controller;

import com.leyou.common.enums.LyExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.pojo.Brand;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.impl.BrandServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("brand")
public class BrandController {

    private static final Logger logger = LoggerFactory.getLogger(Brand.class);

    @Autowired
    private BrandService brandService;

    @GetMapping("page")
    public ResponseEntity<PageResult<BrandDTO>> queryBrandByPage(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "rows", defaultValue = "5") Integer rows,
            @RequestParam(value = "key", required = false) String key,
            @RequestParam(value = "sortBy", required = false) String sortBy,
            @RequestParam(value = "desc", defaultValue = "false") Boolean desc
    ) {
        logger.info("BrandController--queryBrandByPage--请求参数: page=" + page + ",rows=" + rows + ",key" + key + ",sortBy=" + sortBy + ",desc=" + desc);
        PageResult<BrandDTO> brandDTOPageResult = brandService.queryBrandByPage(page, rows, key, sortBy, desc);
        logger.info("BrandController--queryBrandByPage--返回数据:" + brandDTOPageResult);
        return ResponseEntity.ok(brandDTOPageResult);
    }

    @PostMapping
    public ResponseEntity<Void> saveBrand(BrandDTO brandDTO, @RequestParam("cids") List<Long> ids) {
        logger.info("BrandController--saveBrand--请求参数:" + brandDTO + ids);
        try {
            brandService.saveBrand(brandDTO, ids);
        } catch (Exception e) {
            e.printStackTrace();
            throw new LyException(LyExceptionEnum.INSERT_OPERATION_FAIL);
        }
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @PutMapping
    public ResponseEntity<Void> updateBrand(BrandDTO brandDTO, @RequestParam("cids") List<Long> ids) {
        logger.info(("BrandController--updaeBrand--请求参数:" + brandDTO + "--" + ids));
        brandService.updateBrand(brandDTO, ids);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }
}
